%==========================================================================
%=  This file is part of the Sound Restoration Project
%=  (c) Copyright Industrial Mathematics Institute
%=                University of South Carolina, Department of Mathematics
%=  ALL RIGHTS RESERVED
%=
%=  Author: Borislav Karaivanov
%==========================================================================

%==========================================================================
% List of the files on which this procedure depends:
%
% none
%
%==========================================================================

%==========================================================================
% The function "patientlyKeepTryingToReadUntilErrorFree" patiently keeps
% trying to read a specified range of frames from a given video object
% until the "read" function finishes error-free (i.e., without generating
% an error statement) for up to a specified time period.
% INPUT: "videoObj" is a video object allowing to pull frames from a video
% file.
% "frameRange" is a single integer or a row vector of two integers
% specifying the index of a single frame or a range of frames to be read
% from the given video object.
% "pausePeriod" is an optional parameter specifying the time to wait before
% another attempt to read the desired frames is made.
% "maxPauseTime" is an optional parameter specifying an upper bound on the 
% cumulative wait time allowed before the reading effort is abandoned.
% OUTPUT: "framesArr" is an array returning the read frames.
%==========================================================================
function framesArr = patientlyKeepTryingToReadUntilErrorFree(videoObj, ...
    frameRange, pausePeriod, maxPauseTime)

if (nargin < 3)
    pausePeriod = 1;
end
if (nargin < 4)
    maxPauseTime = 10;
end

% Handle the case when the function is called with a single frame index
% specified as a single number (rather than a row vector with two identical
% entries).
frameRange = [frameRange(1), frameRange(end)];

totalPauseTime = 0;
while (totalPauseTime <= maxPauseTime)
    try
        % Try to read in the desired frames.
        framesArr = read(videoObj, frameRange);
        % If the frame does not appear to be constant, then we are done.
        if ( (max(framesArr(:)) - min(framesArr(:))) > 0.00001 )
            return;
        end
    end
    % Wait some time.
    pause(pausePeriod);
    % Keep track of the total time waited so far.
    totalPauseTime = totalPauseTime + pausePeriod;
end

error('SoundRestoration:patientlyKeepTryingToReadUntilErrorFree:ReadFailedToFinishErrorFree', ...
    ['The "read" function failed to finish without error while attempting to read the frame range [' ...
    num2str(frameRange(1)) ',' num2str(frameRange(end)) ...
    '] in up to '  num2str(totalPauseTime) 'seconds.']);

% end of the function "patientlyKeepTryingToReadUntilErrorFree"
